import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { DialogQueue } from '@/utils/dialogQueue'
import { agencyAsync } from '@/appox/appox'
import { appoxEnums } from '@/appox/appox'

export const useBusProtocolChooserStore = defineStore('busProtocolChooser', () => {
  // 状态
  const dialogQueue = new DialogQueue()
  const protocolList = ref([])
  const selectedProtocols = ref([])
  const isConfirmed = ref(false)

  // 计算属性
  const canConfirm = computed(() => {
    return selectedProtocols.value.length > 0 && 
           selectedProtocols.value.every(protocol => 
             protocol.state === appoxEnums.BusProtocolFileState.OK && !protocol.isSelected
           )
  })

  // 动作
  async function initialize(originSelection = []) {
    selectedProtocols.value = []
    isConfirmed.value = false
    protocolList.value = []

    try {
      // 获取协议文件列表
      const idList = await agencyAsync.getBusProtocolFileIDList()
      
      // 并发获取所有文件状态
      const statePromises = idList.map(id => agencyAsync.getBusProtocolFileState(id))
      const states = await Promise.all(statePromises)

      // 构建协议列表
      protocolList.value = idList.map((id, index) => {
        const state = states[index]
        const isSelected = originSelection.some(selected => 
          selected.fileName === id.fileName && selected.md5 === id.md5
        )

        return {
          id,
          state,
          isSelected,
          fileName: id.fileName
        }
      })
    } catch (error) {
      console.error('Failed to load protocol list:', error)
    }
  }

  function selectProtocol(protocol) {
    if (protocol.state === appoxEnums.BusProtocolFileState.OK && !protocol.isSelected) {
      const index = selectedProtocols.value.findIndex(p => p.fileName === protocol.fileName)
      if (index === -1) {
        selectedProtocols.value.push(protocol)
      } else {
        selectedProtocols.value.splice(index, 1)
      }
    }
  }

  function confirm() {
    if (selectedProtocols.value.length > 0) {
      isConfirmed.value = true
      dialogQueue.hide(selectedProtocols.value.map(protocol => protocol.id))
    }
  }

  function cancel() {
    dialogQueue.hide(null)
  }

  function show(originSelection = []) {
    return dialogQueue.show({
      onLoaded: () => initialize(originSelection)
    })
  }

  function hide() {
    if (isConfirmed.value && selectedProtocols.value.length > 0) {
      dialogQueue.hide(selectedProtocols.value.map(protocol => protocol.id))
    } else {
      dialogQueue.hide(null)
    }
  }

  return {
    // 状态
    isVisible: dialogQueue.isVisible,
    protocolList,
    selectedProtocols,
    isConfirmed,
    // 计算属性
    canConfirm,
    // 动作
    initialize,
    selectProtocol,
    confirm,
    cancel,
    show,
    hide,
    getQueueLength: dialogQueue.getQueueLength.bind(dialogQueue),
    clearQueue: dialogQueue.clearQueue.bind(dialogQueue)
  }
})